<template>
    <div>
        <hs-breadcrumb :breadcrumb="breadcrumb"></hs-breadcrumb>
        <Card :bordered="false" :style="{marginBottom:'10px'}">
            <div class="hs-screen-row">
                <Input v-model="params.mallOrderCode" placeholder="订单编号" clearable style="width: 200px"/>
            </div>
            <div class="hs-screen-row">
                <Input v-model="params.username" placeholder="手机号" clearable style="width: 200px"/>
            </div>
            <div class="hs-screen-row">
                <Input v-model="params.nickName" placeholder="昵称" clearable style="width: 200px"/>
            </div>
            <div class="hs-screen-row">
                <Input v-model="params.consigneeName" placeholder="收货人姓名" clearable style="width: 200px"/>
            </div>
            <div class="hs-screen-row">
                <Input v-model="params.consigneePhone" placeholder="收货人手机号" clearable style="width: 200px"/>
            </div>
            <div class="hs-screen-row">
                <Select v-model="params.orderState" placeholder="订单状态" clearable style="width:200px">
                    <Option value="">全部</Option>
                    <Option value="1">待付款</Option>
                    <Option value="2">待发货</Option>
                    <Option value="3">待收货</Option>
                    <Option value="4">已完成</Option>
                    <Option value="5">交易关闭</Option>
                </Select>
            </div>
            <div class="hs-screen-row">
                <DatePicker @on-change="changeDate" v-model="dateInit" type="daterange" :editable="false"
                            separator=" ~ " split-panels transfer
                            placeholder="创建时间" style="width: 200px"></DatePicker>
            </div>
            <div class="hs-screen-row">
                <Button type="primary" @click="findOrderMallList">查询</Button>
            </div>
            <div class="hs-screen-row">
                <Button @click="resetScreen">重置</Button>
            </div>
        </Card>

        <Card :bordered="false" :style="{marginBottom:'10px'}">
            <!--标题-->
            <div slot="title">
                <div class="hs-screen-box">
                    <div>订单列表</div>
                    <div>
                        <ButtonGroup>
                            <Button @click="findOrderMallList">
                                <Icon type="md-refresh" size="15"/>
                            </Button>
                        </ButtonGroup>
                    </div>
                </div>
            </div>

            <div style="margin-bottom: 10px">
                <Button type="dashed" @click="batchOpe">导出订单</Button>
                <Button style="margin-left: 10px" type="dashed" @click="isShowImport = true">导入发货</Button>
            </div>

            <!--表格数据-->
            <Table :columns="columns" :data="data" size="small" :stripe="true" :loading="isTableLoading"
                   @on-select="selectTable" @on-select-cancel="selectCancelTable" @on-select-all="selectAllTable"
                   @on-select-all-cancel="selectAllCancelTable">

                <template slot-scope="{ row, index }" slot="orderState">
                    <span v-if="row.orderState == 1"><Tag color="success">待付款</Tag></span>
                    <span v-if="row.orderState == 2"><Tag color="warning">待发货</Tag></span>
                    <span v-if="row.orderState == 3"><Tag color="primary">待收货</Tag></span>
                    <span v-if="row.orderState == 4"><Tag color="default">已完成</Tag></span>
                    <span v-if="row.orderState == 5"><Tag color="default">交易关闭</Tag></span>
                </template>

                <template slot-scope="{ row, index }" slot="totalFreight">
                    <span>{{row.totalFreight ? row.totalFreight : 0}}</span>
                </template>

                <template slot-scope="{ row, index }" slot="balanceDeduction">
                    <span>{{row.balanceDeduction ? row.balanceDeduction : '-'}}</span>
                </template>

                <template slot-scope="{ row, index }" slot="payMethod">
                    <span v-if="row.payMethod == 'alipay'">支付宝支付</span>
                    <span v-if="row.payMethod == 'wechat'">微信支付</span>
                    <span v-if="!row.payMethod">-</span>
                </template>

                <template slot-scope="{ row, index }" slot="payAmount">
                    <span v-if="row.payAmount">{{row.payAmount}}</span>
                    <span v-else>-</span>
                </template>

                <template slot-scope="{ row }" slot="action">
                    <Button type="success" size="small" style="margin-right: 5px" @click="showOrderOpe(row)">查看
                    </Button>
                    <Button type="primary" size="small" style="margin-right: 5px"
                            @click="showOrderLogisticsNumber(row, 1)" v-if="row.orderState == 2">发货
                    </Button>
                    <Button type="primary" size="small" style="margin-right: 5px"
                            @click="showOrderLogisticsNumber(row, 2)"
                            v-if="row.orderState >= 3 && row.orderState <= 5">修改单号
                    </Button>

                    <Dropdown transfer trigger="click">
                        <Button size="small">
                            <Icon type="ios-more" size="22"/>
                        </Button>
                        <DropdownMenu slot="list">
                            <DropdownItem @click.native="isOrderCancel(row)" v-if="row.orderState <= 2">取消订单
                            </DropdownItem>
                            <DropdownItem @click.native="isDeleteOrderMall(row)" v-if="row.orderState >= 4">删除
                            </DropdownItem>
                            <DropdownItem @click.native="showOrderLogisticsTracking(row)" v-if="row.orderState >= 3">
                                物流跟踪
                            </DropdownItem>
                            <DropdownItem @click.native="showOrderCustomRefund(row, 3)" v-if="row.orderState == 4">
                                自定义退款
                            </DropdownItem>
                        </DropdownMenu>
                    </Dropdown>
                </template>
            </Table>
            <!--分页-->
            <div class="hs-page">
                <Page :total="total" show-sizer show-total transfer @on-change="changePage"
                      @on-page-size-change="changePageSize"/>
            </div>
        </Card>

        <!--显示模态框-->
        <order-ope ref="orderOpe"></order-ope>
        <!--物流跟踪-->
        <order-logistics-tracking ref="orderLogisticsTracking"></order-logistics-tracking>
        <!--发货/修改物流信息-->
        <order-logistics-number ref="orderLogisticsNumber" @changeDate="findOrderMallList"></order-logistics-number>
        <!--自定义退款-->
        <order-custom-refund ref="orderCustomRefund" @changeDate="findOrderMallList"></order-custom-refund>
        <!--显示上传Excel-->
        <Modal v-model="isShowImport" title="导入发货" :mask-closable="false">
            <Alert show-icon closable>重要提示：已发货的订单，在导入发货时会归纳为失败；</Alert>
            <Upload ref="importExcel" :action="action" :headers="headers" :show-upload-list="false"
                    name="file" :on-success="uploadSuccess" :before-upload="beforeUpload" :on-error="onError">
                <div class="hs-upload-image-box">
                    <div class="hs-upload-add">
                        <Icon type="md-add" size="30"/>
                    </div>
                </div>
            </Upload>
            <div class="z-import-message">导入发货成功 {{importSuccess}} 条，失败 {{importFailed}} 条。</div>
            <Table :columns="failOrderColumns" :data="failOrderData" size="small" :stripe="true"></Table>
        </Modal>
    </div>
</template>

<script>
    import hsBreadcrumb from '@/components/hs-breadcrumb';
    import orderOpe from './components/order-ope';
    import orderLogisticsTracking from './components/order-logistics-tracking';
    import orderLogisticsNumber from './components/order-logistics-number';
    import orderCustomRefund from './components/order-custom-refund';


    export default {
        name: "admin",
        data() {
            return {
                total: 0,
                importSuccess:0,
                importFailed:0,
                dateInit: '',
                isTableLoading: false,
                isShowImport: false,
                // 选中数据
                selectData: [],
                action: this.$apiURL + '/orderMall/importOrderExcel',
                headers: {
                    token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
                },
                // 参数
                params: {
                    page: 1,
                    rows: 10,
                    mallOrderCode: '',
                    orderState: '',
                    nickName: '',
                    username: '',
                    consigneeName: '',
                    consigneePhone: '',
                    startTime: '',
                    endTime: '',
                    mallOrderIds: ''
                },
                // 表格列
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        type: 'index',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: 'ID',
                        minWidth: 120,
                        key: 'mallOrderId'
                    },
                    {
                        title: '订单编号',
                        minWidth: 190,
                        key: 'mallOrderCode'
                    },
                    {
                        title: '订单标题',
                        minWidth: 280,
                        key: 'orderTitle',
                        ellipsis: true
                    },
                    {
                        title: '订单金额（元）',
                        minWidth: 120,
                        key: 'totalAmount'
                    },
                    {
                        title: '赠送知豆（个）',
                        minWidth: 120,
                        key: 'integral'
                    },
                    {
                        title: '运费（元）',
                        minWidth: 120,
                        slot: 'totalFreight'
                    },
                    {
                        title: '收货人姓名',
                        minWidth: 120,
                        key: 'consigneeName'
                    },
                    {
                        title: '收货人手机号',
                        minWidth: 120,
                        key: 'consigneePhone'
                    },
                    {
                        title: '下单账号',
                        minWidth: 120,
                        key: 'username'
                    },
                    {
                        title: '下单昵称',
                        minWidth: 180,
                        key: 'nickName',
                        ellipsis: true
                    },
                    {
                        title: '余额抵扣（元）',
                        minWidth: 120,
                        slot: 'balanceDeduction'
                    },
                    {
                        title: '支付方式',
                        minWidth: 120,
                        slot: 'payMethod'
                    },
                    {
                        title: '支付金额（元）',
                        minWidth: 120,
                        slot: 'payAmount'
                    },
                    {
                        title: '订单状态',
                        slot: 'orderState',
                        align: 'center',
                        width: 120
                    },
                    {
                        title: '创建时间',
                        key: 'createTime',
                        width: 150
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        minWidth: 200,
                        align: 'center'
                    }
                ],
                // 表格数据
                data: [],
                failOrderColumns:[
                    {
                        title: '订单编号',
                        minWidth: 190,
                        key: 'orderCode'
                    },
                    {
                        title: '订单标题',
                        minWidth: 280,
                        key: 'orderTitle',
                        ellipsis: true
                    }
                ],
                failOrderData:[],
                // 面包屑
                breadcrumb: [
                    {name: '首页', url: '', icon: 'ios-home-outline', size: 18},
                    {name: '系统管理', url: '', icon: '', size: 0},
                    {name: '订单列表', url: '', icon: '', size: 0}
                ]
            }
        },
        created() {
            // 订单-列表查询
            this.findOrderMallList();
        },
        methods: {
            // 订单-列表查询
            findOrderMallList() {
                this.isTableLoading = true;
                this.axios.post('/orderMall/findOrderMallList', this.params).then(res => {
                    console.log(res);
                    this.isTableLoading = false;
                    if (res.status == 200) {
                        this.total = res.data.total;
                        this.data = res.data.rows;
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '查询订单列表接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 是否取消订单
            isOrderCancel(row) {
                this.$Modal.confirm({
                    title: `是否取消当前订单？`,
                    onOk: () => {
                        // this.$Message.info('您点击了确定.');
                        this.orderCancel(row);
                    },
                    onCancel: () => {
                        this.$Message.info('您点击了取消.');
                    }
                });
            },
            // 是否删除订单
            isDeleteOrderMall(row) {
                // console.log(row)
                this.$Modal.confirm({
                    title: `是否删除当前订单？`,
                    onOk: () => {
                        // this.$Message.info('您点击了确定.');
                        this.deleteOrderMall(row);
                    },
                    onCancel: () => {
                        this.$Message.info('您点击了取消.');
                    }
                });
            },
            // 取消订单
            orderCancel(row) {
                this.$Spin.show();
                this.axios.post('/orderMall/orderCancel', {
                    mallOrderId: row.mallOrderId
                }).then(res => {
                    console.log(res);
                    setTimeout(() => {
                        this.$Spin.hide();
                    }, 300);
                    if (res.status == 200) {
                        this.$Message.success('操作成功.');
                        this.findOrderMallList();
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '取消订单接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 删除订单
            deleteOrderMall(row) {
                this.$Spin.show();
                this.axios.post('/orderMall/deleteOrderMall', {
                    mallOrderId: row.mallOrderId
                }).then(res => {
                    console.log(res);
                    setTimeout(() => {
                        this.$Spin.hide();
                    }, 300);
                    if (res.status == 200) {
                        this.$Message.success('操作成功.');
                        this.findOrderMallList();
                    }
                    if (res.status == 201) {
                        // this.$Message.error(res.msg);
                        this.$Notice.error({
                            title: '删除订单失败',
                            desc: res.msg
                        });
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '删除订单接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 导出订单Excel
            exportExcel() {
                this.$Spin.show();
                this.axios.post('/orderMall/exportExcel', this.params, {
                    responseType: 'arraybuffer'
                }).then(res => {
                    console.log(res);
                    setTimeout(() => {
                        this.$Spin.hide();
                    }, 300);
                    // console.log(res);
                    let blob = new Blob([res], {type: 'Files'});
                    let csvUrl = URL.createObjectURL(blob);
                    let link = document.createElement('a');
                    link.href = csvUrl;
                    // 下载xlsx文件
                    link.download = "商品订单列表.xls";
                    link.click();
                    if (res.status == 201) {
                        // this.$Message.error(res.msg);
                        this.$Notice.error({
                            title: '删除订单失败',
                            desc: res.msg
                        });
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '删除订单接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 显示操作模态框
            showOrderOpe(row) {
                this.$refs.orderOpe.show(row);
            },
            // 显示物流跟踪
            showOrderLogisticsTracking(row) {
                this.$refs.orderLogisticsTracking.show(row);
            },
            // 发货，修改物流信息
            showOrderLogisticsNumber(row, type) {
                this.$refs.orderLogisticsNumber.show(row, type);
            },
            // 显示自定义退款页面
            showOrderCustomRefund(row, type) {
                this.$refs.orderCustomRefund.show(row, type);
            },
            // 日期条件赋值
            changeDate(e) {
                this.params.startTime = e[0];
                this.params.endTime = e[1];
            },
            // 重置筛选条件
            resetScreen() {
                this.params.mallOrderCode = '';
                this.params.orderState = '';
                this.params.nickName = '';
                this.params.username = '';
                this.params.consigneeName = '';
                this.params.consigneePhone = '';
                this.params.startTime = '';
                this.params.endTime = '';
                this.dateInit = '';
            },
            // 改变页数
            changePage(e) {
                this.params.page = e;
                this.findOrderMallList();
            },
            // 改变页容量
            changePageSize(e) {
                this.params.rows = e;
                this.findOrderMallList();
            },
            // 在多选模式下有效，选中某一项时触发
            selectTable(selection, row) {
                this.selectData = selection;
            },
            // 在多选模式下有效，取消选中某一项时触发
            selectCancelTable(selection, row) {
                this.selectData = selection;
            },
            // 在多选模式下有效，点击全选时触发
            selectAllTable(selection) {
                this.selectData = selection;
            },
            // 在多选模式下有效，点击取消全选时触发
            selectAllCancelTable(selection) {
                this.selectData = selection;
            },
            batchOpe() {
                let arr = [];
                if (this.selectData.length) {
                    this.selectData.forEach(v => {
                        arr.push(v.mallOrderId)
                    })
                }
                this.params.mallOrderIds = arr.join(',');
                if (this.params.mallOrderIds) {
                    this.$Modal.confirm({
                        title: `确定导出选中的订单？`,
                        onOk: () => {
                            // this.$Message.info('您点击了确定.');
                            this.exportExcel();
                        },
                        onCancel: () => {
                            this.$Message.info('您点击了取消.');
                        }
                    });
                } else {
                    this.$Modal.confirm({
                        title: `确定导出订单？`,
                        onOk: () => {
                            // this.$Message.info('您点击了确定.');
                            this.exportExcel();
                        },
                        onCancel: () => {
                            this.$Message.info('您点击了取消.');
                        }
                    });
                }
            },
            // 上传之前
            beforeUpload(){
                this.$Spin.show();
            },
            // 上传失败
            onError(){
                this.$Spin.hide();
                this.$Message.error('上传出错！')
            },
            // 导入excel成功之后返回的数据
            uploadSuccess(response, file, fileList) {
                console.log(response)
                setTimeout(() => {
                    this.$Spin.hide();
                }, 300);
                if (response.status == 200) {
                    this.$Message.success('操作成功');
                    this.importSuccess = response.data.successNum;
                    this.importFailed = response.data.failureNum;
                    this.failOrderData = response.data.failOrder;
                }
                if (response.status == 201) {
                    this.$Message.error(response.msg);
                }
                if (response.status == 500) {
                    this.$Notice.error({
                        title: '服务器内部错误',
                        desc: '上传商品组图接口报错',
                        duration: 0
                    });
                }
            },
        },
        components: {
            hsBreadcrumb,
            orderOpe,
            orderLogisticsTracking,
            orderLogisticsNumber,
            orderCustomRefund
        }
    }
</script>

<style scoped lang="less">
    .hs-upload-image-box {
        width: 485px;
        display: flex;
        align-items: center;
        justify-content: center;

        .hs-upload-add {
            cursor: pointer;
            width: 100%;
            height: 43px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px dashed #cccccc;
            transition: all .3s;

            &:hover {
                color: #2d8cf0;
                border: 1px dashed #2d8cf0;
            }
        }
    }
    .z-import-message{
        margin: 10px 0;
    }
</style>